package com.laikan.reader.bookreader.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.*;
import cn.sharesdk.framework.ShareSDK;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.DataSource;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
import com.facebook.imagepipeline.image.CloseableImage;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.helpers.BasicEvent;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.AndroidUtils;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.apirequester.BookDesRequester;
import com.laikan.reader.bookfriend.activity.LoginActivity;
import com.laikan.reader.bookstart.activity.HomeActivity;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.adapter.BookDesCommentAdapter;
import com.laikan.reader.core.bean.*;
import com.laikan.reader.core.events.LaiKanEvent;
import com.laikan.reader.core.utils.*;
import com.laikan.reader.core.view.*;
import com.laikan.reader.database.Book;
import com.laikan.reader.database.DBBook;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;
import thirdparty.cn.sharesdk.onekeyshare.OnekeyShare;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.laikan.reader.R.string.laikan_data_load_failed;
import static com.laikan.reader.R.string.laikan_network_anomaly;

/**
 * 书籍详情页
 */
@SuppressLint ("HandlerLeak")
public class BookDesActivity extends BasicActivity {

    private List<String> mFileList = new ArrayList<String>();
    private TextView book_num, book_name, book_zuozhe;
    private IntroduceText book_des;
    private TextView book_over;
    private String book_id;
    private LinearLayout tuijian_lin, des_read;
    private RelativeLayout des_mybook, des_download;
    private SimpleTagImageView book_img;
    private TextView collect_flag1, chapter;
    private ImageView back_tv, iv_fold_text;
    private File Filejson = null;
    private String bookname, writername;
    private TextView yuepiao, update_time1;
    private boolean open_flag;
    private ArrayList<ChapterBean> mData;
    private RelativeLayout new_chap_rel, all_lin;
    private String chapterId, qdp, tjp, trend, top10, goldNum, goldMatchCount;
    private ImageView icon_home, image_vote, trend1, icon_share;
    private boolean isgold, isOver;
    private Book bookDes;
    private Bundle bundle;
    private int screenWidth, screeHeight;
    private int width_tuijian;
    private TextView des_seemore;
    private ListView comment_list;
    private ArrayList<CommentBean> mcData;
    private BookDesCommentAdapter mcAdapter;
    private LinearLayout des_dashang, des_tuijian, des_fensi;
    private TextView recommend_number;
    private LinearLayout authorbook_linea;
    private TextView reward_number, fans_number, book_sort, discountPrice, price;
    private RelativeLayout rela_des;
    private LinearLayout lin_des_announce;
    private TextView comment_image;
    private boolean comment_flag = false;
    private BaseDataBean<BookDetailBean<Book>> result;
    private BookDetailBean<Book> bookDetail;

    private String BookType = "";
    private String countPrice;
    private TextView down_text;
    private File mFileName;
    private TextView vote_like;
    private TextView registerdate, copyrightinformation;
    private boolean isLoveFlag = false;
    //    private LinearLayout zuozhetushu;
    private String userGoldMatchCount = "", userSupportCount = "";
    private ArrayList<ChapterBean> chapterData;
    private String realPrice;// 书的真实价格
    private ImageViewPullScroll scrollview;
    private RelativeLayout rela_title;
    private RelativeLayout title, common_loaddata_notice;
    private LinearLayout des_new_bottom, bottom;
    private SimpleDraweeView title_image;
    private Bitmap matrixPull;
    private TextView text_title;
    private RelativeLayout re_chapter;
    private LinearLayout linean_tag;
    Drawable drawable_back_tv, drawable_home;
    private View top_line;
    private RelativeLayout back_layout;
    private ImageView jiantou, iv_replace_bookrecommend, iv_title_bg;
    private RelativeLayout reward_layout;
    private TextView reward_number_new, common_prompt_content, common_refresh_net;
    private Book book;
    private LinearLayout limitedfree_layout, ll_replace_bookrecommend;
    private ArrayList<String> rewardIcon = new ArrayList<String>();
    private SimpleDraweeView person_img1, person_img2, person_img3, person_img4, person_img5;
    private Drawable drawable_xiangdu_img, book_introduce_down_arrow, iv_bookrecommend;
    private LoadingDialog mLoadingDialog;
    private CircleProgressBar comon_bgbar_loading;
    private boolean mIsOpenIntroduceText;
    private boolean mIsClickToSupportSuccess = true;
    private View broad;
    private long mLoadingInternalTime;
    private FastBlur fastBlur;
    private TextView line;
    // 点击回复的TextView对象
    TextView tv_reply;
    private boolean is_Showed = false;
//    private boolean shear_is_showing = false; //分享界面是否显示
    private String censusType = "";
    private static final int BLUR_IMG = 0;
    private static final int DOWNLOAD_IMG = 1;
    private boolean isFromPoster = false;

    Handler handler = new Handler() {

        @TargetApi (Build.VERSION_CODES.JELLY_BEAN)
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case BLUR_IMG:
                    fastBlur.setBitmap((Bitmap)msg.obj);
                    break;
                case DOWNLOAD_IMG:
                    title_image.setBackground(new BitmapDrawable((Bitmap)msg.obj));
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private Bitmap setImage(Bitmap bitmap) {
        //获取屏幕的宽高

        int fixHeight = (int)(screeHeight * (354f / 1136f));
        int newHeight = bitmap.getWidth() * fixHeight / screenWidth;
        return BimapUtil.scaleImage(Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), newHeight), screenWidth, fixHeight);

    }

    @Override
    protected void assignViews() {
        fastBlur = new FastBlur();
        fastBlur.setFastListener(new FastBlur.FastBlurInterFace() {
            @Override
            public void callBitmap(Bitmap bitmap) {
                if(bitmap != null){
                    Message message = new Message();
                    message.obj = bitmap;
                    message.what = DOWNLOAD_IMG;
                    handler.sendMessage(message);
                }
            }
        });
        mLoadingDialog = new LoadingDialog(mContext);
        openEventBus();
        setContentView(R.layout.lk_book_newdes_over);
        reward_layout = (RelativeLayout)findViewById(R.id.reward_layout);
        reward_number_new = (TextView)findViewById(R.id.reward_number_new);
        top_line = findViewById(R.id.top_divider);
        linean_tag = (LinearLayout)findViewById(R.id.linean_tag);
        re_chapter = (RelativeLayout)findViewById(R.id.re_chapter);
        text_title = (TextView)findViewById(R.id.text_title);
        title = (RelativeLayout)findViewById(R.id.rl_title);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        title_image = (SimpleDraweeView)findViewById(R.id.title_image);
        rela_title = (RelativeLayout)findViewById(R.id.rela_title);
        des_new_bottom = (LinearLayout)findViewById(R.id.des_new_bottom);
        bottom = (LinearLayout)findViewById(R.id.bottom);
        scrollview = (ImageViewPullScroll)findViewById(R.id.scrollview);
        registerdate = (TextView)findViewById(R.id.registerdate);
        copyrightinformation = (TextView)findViewById(R.id.copyrightinformation);
        down_text = (TextView)findViewById(R.id.down_text);
        vote_like = (TextView)findViewById(R.id.vote_like);
        comment_image = (TextView)findViewById(R.id.comment_image);//暂无评论
        lin_des_announce = (LinearLayout)findViewById(R.id.lin_des_announce);
        rela_des = (RelativeLayout)findViewById(R.id.rela_des);
        book_sort = (TextView)findViewById(R.id.book_sort);
        discountPrice = (TextView)findViewById(R.id.discountPrice);
        price = (TextView)findViewById(R.id.price);
        fans_number = (TextView)findViewById(R.id.fans_number);
        reward_number = (TextView)findViewById(R.id.reward_number);
        authorbook_linea = (LinearLayout)findViewById(R.id.authorbook_linea);
        recommend_number = (TextView)findViewById(R.id.recommend_number);
        des_seemore = (TextView)findViewById(R.id.des_seemore); //全部评论
        des_dashang = (LinearLayout)findViewById(R.id.des_dashang);
        des_tuijian = (LinearLayout)findViewById(R.id.des_tuijian);
        des_fensi = (LinearLayout)findViewById(R.id.des_fensi);
        icon_share = (ImageView)findViewById(R.id.icon_share);
        des_mybook = (RelativeLayout)findViewById(R.id.des_mybook);
        des_download = (RelativeLayout)findViewById(R.id.des_download);
        des_read = (LinearLayout)findViewById(R.id.des_read);
        icon_home = (ImageView)findViewById(R.id.icon_home);
        collect_flag1 = (TextView)findViewById(R.id.collect_flag1);
        all_lin = (RelativeLayout)findViewById(R.id.all_lin);
        chapter = (TextView)findViewById(R.id.chapter);
        update_time1 = (TextView)findViewById(R.id.update_time1);
        yuepiao = (TextView)findViewById(R.id.yuepiao);
        book_num = (TextView)findViewById(R.id.book_num);
        book_name = (TextView)findViewById(R.id.book_name);
        book_zuozhe = (TextView)findViewById(R.id.book_zuozhe);
        book_over = (TextView)findViewById(R.id.book_over);
        book_des = (IntroduceText)findViewById(R.id.book_des);
        tuijian_lin = (LinearLayout)findViewById(R.id.tuijian_lin);
        book_img = (SimpleTagImageView)findViewById(R.id.book_img);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        iv_fold_text = (ImageView)findViewById(R.id.iv_fold_text);
        iv_replace_bookrecommend = (ImageView)findViewById(R.id.iv_replace_bookrecommend);
        ll_replace_bookrecommend = (LinearLayout)findViewById(R.id.ll_replace_bookrecommend);
        iv_title_bg = (ImageView)findViewById(R.id.iv_title_bg);
        common_prompt_content = (TextView)findViewById(R.id.common_prompt_content);
        common_refresh_net = (TextView)findViewById(R.id.common_refresh_net);
        broad = (View)findViewById(R.id.broad);
        common_loaddata_notice = (RelativeLayout)findViewById(R.id.common_loaddata_notice);
        comon_bgbar_loading = (CircleProgressBar)findViewById(R.id.comon_bgbar_loading);


        line = (TextView)findViewById(R.id.line);
        // getDatass();
        limitedfree_layout = (LinearLayout)findViewById(R.id.limitedfree_layout);
        comment_list = (ListView)findViewById(R.id.comment_listview);
        comment_list.setFocusable(false);
        comment_list.setFocusableInTouchMode(false);
        person_img1 = (SimpleDraweeView)findViewById(R.id.person_img1);
        person_img2 = (SimpleDraweeView)findViewById(R.id.person_img2);
        person_img3 = (SimpleDraweeView)findViewById(R.id.person_img3);
        person_img4 = (SimpleDraweeView)findViewById(R.id.person_img4);
        person_img5 = (SimpleDraweeView)findViewById(R.id.person_img5);
    }

    @Override
    protected void parseEvent(BasicEvent event) {
        switch (event.getEventID()) {
            case LaiKanEvent.EVENT_ID_BOOK_REFRESH_RECOMMENDBOOK:
                BookRecommendBean.RecommendBook recommend = (BookRecommendBean.RecommendBook)event.getEventMap().get("recommendbook");
                if (recommend != null) {
                    ArrayList<Book> recommendBookList = recommend.getRecommendBookList();
                    bookDetail.setTuijian(recommendBookList);
                    bookDetail.setSortId(recommend.getSortId());
                    addRecommendBook();
                }else {
                    String requestStatus = (String)event.getEventMap().get("status");
                    if(!TextUtils.isEmpty(requestStatus) && requestStatus.equals("netfailed")){
                        ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                    }else if(!TextUtils.isEmpty(requestStatus) && requestStatus.equals("datafailed")){
                        ToastMgr.showShortToast(laikan_data_load_failed);
                    }
                }
                iv_replace_bookrecommend.clearAnimation();
                ll_replace_bookrecommend.setOnClickListener(BookDesActivity.this);
                break;
            case LaiKanEvent.EVENT_ID_BOOK_REFRESH_REPLY_NUMBER:
                try {
                    String totalReply = (String)event.getEventMap().get("totalreply");
                    String totalLikeCount = (String)event.getEventMap().get("totallikecount");
                    boolean isFavor = (boolean)event.getEventMap().get("isFavor");
                    KLog.e(" totalReply : " + totalReply + " totalLikeCount " + totalLikeCount);
                    String replyid = (String)event.getEventMap().get("replyId");
                    ArrayList<CommentBean> commentBeenList = bookDetail.getReviewList();
                    for (int i = 0; i < commentBeenList.size(); i++) {
                        String clickReplyId = commentBeenList.get(i).getReviewId();
                        if (!TextUtils.isEmpty(totalReply) && clickReplyId.equals(replyid)) {
                            bookDetail.getReviewList().get(i).setReplyCount(totalReply);
                        }
                        if (!TextUtils.isEmpty(totalLikeCount) && clickReplyId.equals(replyid)) {
                            bookDetail.getReviewList().get(i).setLikeCount(totalLikeCount);
                            bookDetail.getReviewList().get(i).setFavor(isFavor);
                        }
                    }
                    mcAdapter.setDatas(bookDetail.getReviewList());
                    mIsClickToSupportSuccess = true;
                }catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void initData() {

        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        drawable_home = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.icon_home_e), Color.parseColor("#66ccdd")));
        //替换分享logo为蓝色
        drawable_xiangdu_img = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_xiangdu_small), Color.parseColor("#66ccdd")));
        book_introduce_down_arrow = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.book_introduce_down_arrow), Color.parseColor("#333333")));
        iv_bookrecommend = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.iv_replace_bookrecommend), Color.parseColor
            ("#cccccc")));
        iv_replace_bookrecommend.setImageDrawable(iv_bookrecommend);
        common_prompt_content.setText(R.string.laikan_network_anomaly);
        // 评论
        mcData = new ArrayList<>();
        mcAdapter = new BookDesCommentAdapter(mContext, mcData);
        comment_list.setAdapter(mcAdapter);

        SPUtil.putBoolean("ticket_refresh", false);
        DisplayMetrics dm = new DisplayMetrics();
        // 获取屏幕信息
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;
        screeHeight = dm.heightPixels;
        width_tuijian = screenWidth / 3;

        if("from_poster".equals(getIntent().getAction())){
            isFromPoster = true;
        }else{
            isFromPoster = false;
        }

        censusType = getIntent().getStringExtra("censusType");
        book = (Book)getIntent().getSerializableExtra("data");
        if (book == null) {
            book_id = getIntent().getStringExtra("bookId");
        }else {
            book_id = book.getId();
            book_img.setImageURI(Uri.parse(book.getIcon()));
            text_title.setText(R.string.activity_title_book_detail);
            book_name.setText(book.getName());
            if (book.getIntroduce() != null) {
                setIntroduceText(book.getIntroduce());
            }
        }
        mData = new ArrayList<ChapterBean>();
        SPUtil.putInt("rewardNumberInt", 0);
        scrollHeadBg();
        if (ActivityUitl.isNetworkAvailable(BookDesActivity.this)) {
            getData(true);
        }else {
            common_prompt_content.setText(R.string.laikan_network_anomaly);
            requestDataResultHandle(false);
        }

    }

    private void requestDataResultHandle(boolean result) {
        common_refresh_net.setOnClickListener(BookDesActivity.this);
        if (result) {
            scrollview.setVisibility(View.VISIBLE);
            bottom.setVisibility(View.VISIBLE);
            broad.setVisibility(View.VISIBLE);
            common_loaddata_notice.setVisibility(View.GONE);
            comon_bgbar_loading.setVisibility(View.VISIBLE);
            setTitleStyle(true);

        }else {
            scrollview.setVisibility(View.GONE);
            bottom.setVisibility(View.GONE);
            broad.setVisibility(View.GONE);
            common_loaddata_notice.setVisibility(View.VISIBLE);
            comon_bgbar_loading.setVisibility(View.INVISIBLE);
            setTitleStyle(false);
        }
    }

    private void setTitleStyle(boolean type) {
        if (type) {
            title.setBackgroundResource(R.color.C_00000000);
            text_title.setVisibility(View.GONE);
            top_line.setVisibility(View.GONE);
            back_tv.setImageResource(R.drawable.lk_back_small);
            icon_share.setVisibility(View.VISIBLE);
            icon_home.setVisibility(View.VISIBLE);
            icon_share.setImageResource(R.drawable.lk_xiangdu_small);
            icon_home.setImageResource(R.drawable.icon_home_e);
        }else {
            text_title.setText(R.string.activity_title_book_detail);
            text_title.setVisibility(View.VISIBLE);
            title.setBackgroundResource(R.color.C_FFFFFF);
            top_line.setVisibility(View.VISIBLE);
            back_tv.setImageDrawable(drawable_back_tv);
            icon_share.setImageDrawable(drawable_xiangdu_img);
            icon_home.setImageDrawable(drawable_home);
            if(common_loaddata_notice.getVisibility() == View.VISIBLE){
                icon_share.setVisibility(View.GONE);
                icon_home.setVisibility(View.GONE);
            }
        }
    }

    public void closeDelayLoading(long currenttime) {
        if (currenttime < mLoadingInternalTime) {
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    comon_bgbar_loading.setVisibility(View.GONE);
                    requestDataResultHandle(false);
                }
            }, 1000);
        }else {
            comon_bgbar_loading.setVisibility(View.GONE);
            requestDataResultHandle(false);
        }
    }

    public void setIntroduceText(final String text) {
        if (book_des.getWidth() <= 0) {
            book_des.setSizeChangeListener(new IntroduceText.SizeChangeListener() {
                @Override
                public void sizeChanged(int w, int h, int oldw, int oldh) {
                    book_des.setSizeChangeListener(null);
                    KLog.e(" textsub: book_des.getWidth()listener " + w + "book_des.getTextSize() " + book_des.getTextSize());
                    setIntroduceTextByLength(text);
                }
            });
        }else {
            setIntroduceTextByLength(text);
        }
    }

    private void setIntroduceTextByLength(String text) {
        int initLines = 4;
        Paint paint = new Paint();
        paint.setTextSize(book_des.getTextSize());
        float contentSize = paint.measureText(text);
        if (contentSize > book_des.getWidth() * initLines - book_des.getTextSize()) {
            mIsOpenIntroduceText = true;
            iv_fold_text.setVisibility(View.VISIBLE);
            iv_fold_text.setImageDrawable(book_introduce_down_arrow);
            int textLength = (int)(((float)book_des.getWidth() / book_des.getTextSize() * 3.8f));
            if (textLength > text.length()) {
                book_des.setText(Html.fromHtml(text));
            }else {
                book_des.setText(Html.fromHtml(text.substring(0, textLength) + "..."));
            }
        }else {
            book_des.setOnClickListener(null);
            book_des.setText(Html.fromHtml(text));
        }
        book_des.setMaxLines(initLines);
    }

    /**
     * 设置头部滚动监听
     */
    private void scrollHeadBg() {
        //        int title_image_width_px = AndroidUtils.dip2px(BookDesActivity.this, show_titlebar_uppull_height_dp);
        //        final int maxOffset = title_image_width_px;
        //        final int onsetOffset = title_image_width_px;
        float show_titlebar_uppull_height_dp = 50.0f;
        final int onsetOffset = AndroidUtils.dip2px(BookDesActivity.this, show_titlebar_uppull_height_dp);
        scrollview.setOnScrollListener(new ImageViewPullScroll.OnScrollListener() {
            @Override
            public void onScroll(int scrollY) {
                if (scrollY < onsetOffset) {
                    setTitleStyle(true);
                }else {
                    setTitleStyle(false);
                }
            }

        });
    }

    @Override
    protected void onResume() {
//        shear_is_showing = false;
        if (SPUtil.getBoolean("reward_refresh", false)) {
            SPUtil.putBoolean("reward_refresh", false);
            getData(false);
        }

        if (SPUtil.getBoolean("comment_refresh", false)) {
            SPUtil.putBoolean("comment_refresh", false);
            getData(false);
        }

        if (SPUtil.getBoolean("ticket_refresh", false)) {
            userGoldMatchCount = SPUtil.getInt("userGoldMatch", 0) + "";
            userSupportCount = SPUtil.getInt("userSupport", 0) + "";
            int num = Integer.parseInt(bookDetail.getSupportCount()) + SPUtil.getInt("tj_ticket", 1);
            tjp = num + "";
            if (bookDetail.getSupportCount().length() > 4) {
            }else {
                recommend_number.setText(num + "");
            }
            SPUtil.putBoolean("ticket_refresh", false);
        }
        if (DBBook.getInstance().queryBookById(book_id) != null) {
            collect_flag1.setText(R.string.bookshelf_already_added);
            collect_flag1.setTextColor(getResources().getColor(R.color.C_999999));
        }else {
            collect_flag1.setText(R.string.bookdes_add_to_bookshelf);
        }
        super.onResume();
        MobclickAgent.onResume(this);
    }

    int position = 0;

    private void doBlur(String uri){
        new FrescoManager.LoadImageFrescoBuilder(mContext, new SimpleDraweeView(mContext), Uri.parse(uri).toString())
            .setBitmapDataSubscriber(new BaseBitmapDataSubscriber() {
                @TargetApi (Build.VERSION_CODES.JELLY_BEAN)
                @Override
                protected void onNewResultImpl(Bitmap bitmap) {
                    if (bitmap != null) {
                        Message msg = new Message();
                        msg.what = BLUR_IMG;
                        msg.obj = bitmap;
                        handler.sendMessage(msg);
                    }
                }

                @Override
                protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {

                }
            }).build();
    }

    /**
     * 数据处理
     *
     * @param
     */

    private void setDate() {

        final String avator_uri;

        linean_tag.setVisibility(View.VISIBLE);
        des_seemore.setText("全部评论(" + bookDetail.getReviewListCount() + "条)");
        if (TextUtils.isEmpty(bookDetail.getLimitedFreeEndTime())) {
            discountPrice.setText(bookDetail.getDiscountPrice());
            discountPrice.setTextColor(getResources().getColor(R.color.C_eebb66));
        }else {
            discountPrice.setTextColor(getResources().getColor(R.color.C_66ccdd));
            limitedfree_layout.setBackgroundResource(R.drawable.lk_btn_border_4_blue);
            book_img.setMaxWidth(15);
            book_img.setTagWidth(15);
            discountPrice.setText(bookDetail.getLimitedFreeEndTime());
        }

        if (book == null) {
            avator_uri = bookDetail.getIcon();
            book_img.setImageURI(Uri.parse(bookDetail.getIcon()));
            text_title.setText(R.string.activity_title_book_detail);
            book_name.setText(bookDetail.getName());
            book_sort.setText(bookDetail.getSortName());
            book_zuozhe.setText(" | " + bookDetail.getAuthorName());
        }else {
            avator_uri = book.getIcon();
            if (TextUtils.isEmpty(book_sort.getText())) {
                book_sort.setText(result.getData().getSortName());
            }
            if (TextUtils.isEmpty(book_zuozhe.getText())) {
                book_zuozhe.setText(" | " + bookDetail.getAuthorName());
            }
        }
        if (TextUtils.isEmpty(book_des.getText())) {
            setIntroduceText(bookDetail.getIntroduce());
        }

        realPrice = bookDetail.getPrice();

        userGoldMatchCount = bookDetail.getUserGoldMatchCount();
        userSupportCount = bookDetail.getUserSupportCount();
        goldMatchCount = bookDetail.getGoldMatchCount();
        isgold = bookDetail.isGolden();
        String publishShowTime = bookDetail.getPublishShowTime();
        if (!publishShowTime.equals("")){
            registerdate.setText("上架时间 : " + publishShowTime);
        }else {
            registerdate.setText(R.string.book_added_time_unknown);
        }
        copyrightinformation.setText("版权信息 : " + bookDetail.getVersion());
        countPrice = "";

        countPrice = bookDetail.getDiscountPrice();
        BookType = bookDetail.getGroup();
        bookname = bookDetail.getName();
        writername = bookDetail.getAuthorName();

        if (BookType.equals("3")) {
            vote_like.setText(R.string.bookdes_like);
            down_text.setText(R.string.reder_detail_buy);
        }else {
            des_download.setBackgroundResource(R.drawable.des_buy_bg);
            vote_like.setText(R.string.des_tuijian_text);
            down_text.setText(R.string.bookdes_preferential_buy);
        }

        // 是否收藏
        if (DBBook.getInstance().queryBookById(book_id) != null) {
            collect_flag1.setText(R.string.bookshelf_already_added);
            collect_flag1.setTextColor(getResources().getColor(R.color.C_999999));
            des_mybook.setOnClickListener(null);
        }else {
            collect_flag1.setText(R.string.bookdes_add_to_bookshelf);
        }
        // 最新更新时间
        // update_time1.setText(PublicUtil.getDateToString(Long.parseLong(bookDetail.getLastChapterList().get(0).getShowTime())) + " 更新");
        if(bookDetail.getLastChapterList()!=null && bookDetail.getLastChapterList().size()!=0){

            update_time1.setText(bookDetail.getLastChapterList().get(0).getChapterShowTime()+ " 更新");
            // 最新章节名称
            // update_name1.setText(bookDetail.getLastChapterList().get(0).getName());
            // 最新章节ID
            chapterId = bookDetail.getLastChapterList().get(0).getId();
        }
        chapter.setText("(共" + bookDetail.getChapterCount() + "章)");
        // 对点击数进行判断，万以上转成万，万以下直接显示点击数
        if (bookDetail.getReadPV().length() > 4) {
            yuepiao.setText(bookDetail.getReadPV().substring(0, bookDetail.getReadPV().length() - 4) + "W点击");
        }else {
            yuepiao.setText(bookDetail.getReadPV() + "点击");
        }
        reward_number_new.setText("共" + bookDetail.getReward() + "次打赏");
        rewardIcon = bookDetail.getDonateList();
        ArrayList<SimpleDraweeView> rewardIconView = new ArrayList<SimpleDraweeView>();
        rewardIconView.add(person_img1);
        rewardIconView.add(person_img2);
        rewardIconView.add(person_img3);
        rewardIconView.add(person_img4);
        rewardIconView.add(person_img5);

        if (rewardIcon != null && rewardIcon.size() > 0) {
            if (rewardIcon.size() == 6) {
                for (int q = 0; q < rewardIcon.size() - 1; q++) {
                    rewardIconView.get(q).setImageURI(Uri.parse(rewardIcon.get(q)));
                }
            }else {
                for (int i = 0; i < rewardIcon.size(); i++) {
                    rewardIconView.get(i).setImageURI(Uri.parse(rewardIcon.get(i)));
                }
            }
            for (int j = rewardIconView.size() - 1; j < 5 - rewardIcon.size(); j++) {
                rewardIconView.get(j).setImageResource(R.drawable.lk_default_personal_image_grey);
            }
        }
        fans_number.setText(bookDetail.getFollowCount());
        // 大于6位数 转换 万
        isLoveFlag = isNumeric(bookDetail.getSupportCount());
        if (!BookType.equals("3")) {
            if (isLoveFlag) {
                if (bookDetail.getSupportCount().length() > 4) {

                    recommend_number.setText(bookDetail.getSupportCount().substring(0, bookDetail.getSupportCount().length() - 4) + "万+");

                }else {
                    recommend_number.setText(bookDetail.getSupportCount());
                }
            }else {
                recommend_number.setText(bookDetail.getSupportCount());
            }
        }else {
            recommend_number.setText(bookDetail.getSupportCount());
        }

        tjp = bookDetail.getSupportCount();
        qdp = bookDetail.getAwaitCount();
        //对字数进行判断，万以上转成万，万以下直接显示字数
        if (bookDetail.getWords().length() > 4) {
            book_num.setText(bookDetail.getWords().substring(0, bookDetail.getWords().length() - 4) + "W字");
        }else {
            book_num.setText(bookDetail.getWords() + "字");
        }
        //判断原价格是否为空，不为空，则显示原价格，字体为灰色，
        if (!TextUtils.isEmpty(bookDetail.getPrice())) {
            price.setText(bookDetail.getPrice());
            price.setTextColor(getResources().getColor(R.color.C_CCCCCC));
            price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); ///文本加中划线
            line.setVisibility(View.VISIBLE);
        }else {
            line.setVisibility(View.GONE);
        }
        // 书籍 是否完结
        if (bookDetail.isFinished()) {
            re_chapter.setVisibility(View.VISIBLE);
            book_over.setText(R.string.bookdes_end);
            isOver = true;
        }else {
            re_chapter.setVisibility(View.VISIBLE);
            book_over.setText(R.string.bookdes_loading);
            isOver = false;
        }

        authorbook_linea.removeAllViews();
        addRecommendBook();
        rela_des.setVisibility(View.VISIBLE);
        all_lin.setVisibility(View.VISIBLE);
        // 书籍简介
        String introduce = bookDetail.getIntroduce();
        // 临时保存书架显示所需书籍信息
        bookDes = new Book();
        bookDes.setAuthorName(writername);
        bookDes.setIcon(bookDetail.getIcon());
        bookDes.setId(bookDetail.getId());
        bookDes.setName(bookname);
        if(bookDetail.getLastChapterList()!=null && bookDetail.getLastChapterList().size()!=0){

            bookDes.setUpdateTime(bookDetail.getLastChapterList().get(0).getShowTime());
        }
        bookDes.setIntroduce(introduce);
        bookDes.setStatus(bookDetail.getStatus());
        new Thread(){
            @Override
            public void run() {
                doBlur(avator_uri);
                super.run();
            }
        }.start();
    }

    private void addRecommendBook() {
        // 推荐书籍
        tuijian_lin.removeAllViews();

        // 处理点击查看某些书籍进入详情界面时,可能导致应用崩溃问题,对推荐书籍数据进行非空判断
        for (int i = 0; bookDetail.getTuijian() != null && bookDetail.getTuijian().size() > 0 && i < 3; i++) {
            position = i;
            View tj = View.inflate(mContext, R.layout.lk_bookdes_tuijian_item_new, null);
            SimpleDraweeView tuijian_img = (SimpleDraweeView)tj.findViewById(R.id.tuijian_img);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            params.weight = 1;
            params.width = width_tuijian;
            tj.setLayoutParams(params);
            TextView book_name = (TextView)tj.findViewById(R.id.book_name);
            LinearLayout search_lin = (LinearLayout)tj.findViewById(R.id.search_lin);
            tuijian_img.setImageURI(Uri.parse(bookDetail.getTuijian().get(i).getIcon()));
            book_name.setText(bookDetail.getTuijian().get(i).getName());
            final String id = bookDetail.getTuijian().get(i).getId();
            search_lin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (position == 0) {
                        MobclickAgent.onEvent(mContext, "information_closebook1");
                    }else if (position == 1) {
                        MobclickAgent.onEvent(mContext, "information_closebook2");
                    }else if (position == 2) {
                        MobclickAgent.onEvent(mContext, "information_closebook3");
                    }

                    if (book_id.equals(id)) {
                        scrollview.fullScroll(View.FOCUS_UP);
                    }else {
                        Intent intent = new Intent();
                        intent.setClass(mContext, BookDesActivity.class);
                        intent.putExtra("bookId", id);
                        startActivity(intent);
                    }
                }
            });

            tuijian_lin.addView(tj);
        }
    }

    /**
     * 访问网络获取数据
     */
    private void getData(boolean is_Showed) {
        if(is_Showed){
            mLoadingDialog.show();
        }
        if(censusType==null){
            censusType = "";
        }
        Map<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));
        map.put("censusType",censusType);
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                mLoadingDialog.dismiss();
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<BookDetailBean<Book>>>() {
                }.getType();
                try {
                    result = new BaseDataBean<>();
                    result = gson.fromJson(httpResponse.responseContent, type);
                    bookDetail = result.getData();
                    if (result != null) {
                        if (null == bookDetail || !Constants.RESULT_OK.equals(result.getResult())) {
                            // 如果此本书 搜索不到 或者网络访问失败 1.5秒后 关闭此页
                            common_prompt_content.setText(laikan_data_load_failed);
                            closeDelayLoading(System.currentTimeMillis());
                        }else {
                            requestDataResultHandle(true);
                            // 设置数据
                            mcAdapter.setDatas(bookDetail.getReviewList());
                            if (bookDetail.getReviewList().size() == 0) {
                                comment_flag = false;
                                comment_image.setVisibility(View.VISIBLE);
                                des_seemore.setVisibility(View.GONE);
                            }else {
                                comment_flag = true;
                                comment_image.setVisibility(View.GONE);
                                des_seemore.setVisibility(View.VISIBLE);
                            }
                            mcAdapter.setItemClickListener(new BookDesCommentAdapter.ItemClickListener() {

                                @Override
                                public void onItemClick(View view, int position) {
                                    //                                    replyComment(position);
                                }

                                @Override
                                public void onClickToSupport(View view, int position) {
                                    if (TextUtils.isEmpty(SPUtil.getString("user_id", "")) || "0".equals(SPUtil.getString("user_id", ""))) {
                                        Intent intent = new Intent(mContext, LoginActivity.class);
                                        startActivity(intent);
                                    }else if(!ActivityUitl.isNetworkAvailable(BookDesActivity.this)) {
                                        ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                                    }else {
                                        if (mIsClickToSupportSuccess){
                                            mIsClickToSupportSuccess = false;
                                            BookDesRequester.clickToSupport(view, bookDetail.getReviewList().get(position).getReviewId(), LaiKanEvent.EVENT_ID_BOOK_REFRESH_REPLY_NUMBER);
                                        }
                                    }
                                }

                                @Override
                                public void onReplyClick(View view, int position) {
                                    tv_reply = (TextView)((RelativeLayout)view).findViewById(R.id.tv_reply);
                                    replyComment(position);
                                }
                            });
                            setDate();
                        }
                    }else {
                        common_prompt_content.setText(laikan_data_load_failed);
                        closeDelayLoading(System.currentTimeMillis());
                    }
                }catch (JsonSyntaxException e) {
                    // 数据解析失败
                    e.printStackTrace();
                    return;
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                common_prompt_content.setText(laikan_network_anomaly);
                closeDelayLoading(System.currentTimeMillis());
                KLog.e("网络不给力，请重试。01");
            }

            @Override
            public void onFinish() {
                mLoadingDialog.dismiss();
            }
        };
        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL2() + "book/" + book_id);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

    }

    private void replyComment(int position) {
        String replyid = bookDetail.getReviewList().get(position).getReviewId();
        Intent intent = new Intent();
        intent.setClass(mContext, CommentDetailActivity.class);
        intent.putExtra("name", bookDetail.getReviewList().get(position).getName());
        intent.putExtra("replyId", replyid.trim());
        intent.putExtra("commentid", bookDetail.getReviewList().get(position).isBest());
        startActivity(intent);
    }

    /**
     * 访问网络获取数据
     */
    private void send() {
        mLoadingDialog.show();
        Map<String, String> map = new HashMap<String, String>();
        map.put("sd", SPUtil.getString("token", ""));

        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                mLoadingDialog.dismiss();
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<BookDetailBean>>() {}.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                    bookDetail = result.getData();
                    if (result != null) {
                        if (null == bookDetail || !Constants.RESULT_OK.equals(result.getResult())) {
                            ToastMgr.showShortToast(result.getError_msg());

                        }else {

                            if (bookDetail.isWasFavor()) {
                                recommend_number.setText(bookDetail.getFavorCount() + "");
                                ToastMgr.showShortToast(R.string.bookdes_setting_like);
                            }else {
                                ToastMgr.showShortToast(R.string.bookdes_cancel_like);
                                recommend_number.setText(bookDetail.getFavorCount() + "");
                            }
                        }
                    }else {
                        ToastMgr.showShortToast(laikan_data_load_failed);
                    }
                }catch (JsonSyntaxException e) {
                    // 数据解析失败
                    ToastMgr.showShortToast(laikan_data_load_failed);
                    e.printStackTrace();
                    return;
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                KLog.e("网络不给力，请重试。02");
                mLoadingDialog.dismiss();
                finish();
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL2() + "book_favorite?sd=" + SPUtil.getString("token", "") + "&bookId=" + book_id);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    @Override
    protected void setListener() {
        title.setOnClickListener(this);
        des_mybook.setOnClickListener(this);
        des_download.setOnClickListener(this);
        des_read.setOnClickListener(this);
        back_layout.setOnClickListener(this);
        icon_share.setOnClickListener(this);
        icon_home.setOnClickListener(this);
        des_dashang.setOnClickListener(this);
        des_tuijian.setOnClickListener(this);
        des_fensi.setOnClickListener(this);
        des_seemore.setOnClickListener(this);
        lin_des_announce.setOnClickListener(this);
        re_chapter.setOnClickListener(this);
        reward_layout.setOnClickListener(this);
        iv_fold_text.setOnClickListener(this);
        book_des.setOnClickListener(this);
        ll_replace_bookrecommend.setOnClickListener(this);
        common_refresh_net.setOnClickListener(this);
        title.setOnClickListener(null);
    }

    @Override
    protected void onClickEvent(View view) {
        switch (view.getId()) {
            //全部评论
            case R.id.des_seemore:
                MobclickAgent.onEvent(mContext, "information_allcomment");
                if (comment_flag) {
                    startActivity(new Intent().setClass(getApplicationContext(), CommentActivity.class).putExtra("bookName", bookname).putExtra("bookId", book_id).putExtra("allow",
                        bookDetail
                        .isAllowRecommend()).putExtra("allowMsg", bookDetail.getAllowRecommendMsg()));
                }else {
                    ToastMgr.showShortToast(R.string.bookdes_no_comment);
                }

                break;
            //写评论
            case R.id.lin_des_announce:
                MobclickAgent.onEvent(mContext, "information_writecomment");
                if (TextUtils.isEmpty(SPUtil.getString("user_id", "")) || "0".equals(SPUtil.getString("user_id", ""))) {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }else if(bookDetail != null){
                    if (bookDetail.isAllowRecommend()) {
                        startActivity(new Intent().setClass(getApplicationContext(), SendCommentActivity.class).setAction("from_book_des").putExtra("bookId", book_id));
                    }else {
                        ToastMgr.showShortToast(bookDetail.getAllowRecommendMsg());
                    }

                }

                break;
            case R.id.reward_layout:  //打赏
                if(bookDetail == null) return;
                MobclickAgent.onEvent(mContext, "details_boost");
                startActivity(new Intent().setClass(mContext, RewardActivityNew.class).putExtra("bookId", book_id).putExtra("bookName", bookname).putExtra("rewardNumber",
                    bookDetail.getReward()));
                break;
            case R.id.des_tuijian:
                MobclickAgent.onEvent(mContext, "details_vote");
                if (!BookType.equals("3")) {
                    startActivity(new Intent().setClass(getApplicationContext(), VoteActivity.class)
                        .putExtra("userGoldMatchCount", userGoldMatchCount)
                        .putExtra("userSupportCount", userSupportCount)
                        .putExtra("bookName", bookname)
                        .putExtra("bookId", book_id)
                        .putExtra("isgold", isgold)
                        .putExtra("isover", isOver)
                        .putExtra("tjp", tjp)
                        .putExtra("qdp", qdp)
                        .putExtra("trend", trend)
                        .putExtra("top10", top10)
                        .putExtra("goldNum", goldMatchCount));
                }

                break;
            case R.id.des_fensi:
                startActivity(new Intent().setClass(mContext, Fans.class)
                    .putExtra("bookId", book_id)
                    .putExtra("bookName", bookname));
                break;

            // 购买界面
            case R.id.des_download:

                MobclickAgent.onEvent(mContext, "information_favourableBuy");

                if (TextUtils.isEmpty(SPUtil.getString("user_id", "")) || "0".equals(SPUtil.getString("user_id", ""))) {

                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }else {
                    if (BookType.equals("3")) {
                        Intent intent = new Intent(mContext, DesBookBuy.class);
                        intent.putExtra("bookName", bookname);
                        intent.putExtra("bookId", book_id);
                        intent.putExtra("discountPrice", countPrice);
                        intent.putExtra("writername", writername);
                        intent.putExtra("fullPrice", realPrice);
                        intent.putExtra("isFollow", DBBook.getInstance().queryBookById(book_id) != null);
                        bundle = new Bundle();
                        bundle.putSerializable("bookDes", bookDes);
                        intent.putExtras(bundle);
                        startActivityForResult(intent, 101);
                        this.overridePendingTransition(R.anim.open, 0);
                    }else {
                        Intent intent = new Intent();
                        // 批量购买修改
                        intent.setClass(mContext, DesChapterBuy.class);
                        intent.putExtra("book_id", book_id);
                        intent.putExtra("bookName", bookname);
                        intent.putExtra("state", "1");
                        intent.putExtra("writername", writername);
                        // 传递书籍详情信息
                        bundle = new Bundle();
                        bundle.putSerializable("bookDes", bookDes);
                        intent.putExtras(bundle);
                        startActivity(intent);
                        this.overridePendingTransition(R.anim.open, 0);
                    }
                }

                break;
            // 立即阅读
            case R.id.des_read:
                MobclickAgent.onEvent(mContext, "information_probation");
                loadDirectory(2);
                break;
            // 加入书架
            case R.id.des_mybook:
                MobclickAgent.onEvent(mContext, "information_addbookshelf");
                if (DBBook.getInstance().queryBookById(book_id) == null) {
                    collect();
                }
                break;
            case R.id.icon_share:
//                if(shear_is_showing){
//                    return;
//                }
//                shear_is_showing = true ;
                if (BookFileUtils.isNoLogin()) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                }else {
                    MobclickAgent.onEvent(mContext, "details_share");
                    ShareSdkReadBookShare.readBookShare(book_id, null, BookDesActivity.this);
                }
                break;
            case R.id.icon_home:
                MobclickAgent.onEvent(mContext, "bookdetail_home");
                startActivity(new Intent(BookDesActivity.this, HomeActivity.class));
                this.finish();
                break;
            case R.id.re_chapter:
                MobclickAgent.onEvent(mContext, "information_list");
                if (mFileList.contains(book_id)) {
                    Intent intent = new Intent();
                    intent.setClass(mContext, BookChapter.class);
                    intent.putExtra("book_id", book_id);
                    intent.putExtra("bookName", bookname);
                    intent.putExtra("state", "1");
                    intent.putExtra("writername", writername);
                    intent.putExtra("groupId", BookType);


                    bundle = new Bundle();
                    bundle.putSerializable("bookDes", bookDes);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }else {
                    loadDirectory(1);
                }
                break;
            case R.id.book_des:
                if(bookDetail == null) return;
                KLog.e("width : " + book_des.getWidth() + "des_new_bottom " + des_new_bottom.getWidth() + "book_des.getTextSize()  " + book_des.getTextSize());
                if (mIsOpenIntroduceText) {
                    mIsOpenIntroduceText = false;
                    book_des.setMaxLines(999);
                    iv_fold_text.setVisibility(View.GONE);
                    book_des.setText(Html.fromHtml(bookDetail.getIntroduce() + "  "));
                }else {
                    mIsOpenIntroduceText = true;
                    iv_fold_text.setVisibility(View.VISIBLE);

                    int textLeng = (int)(((float)book_des.getWidth() / book_des.getTextSize() * 3.8f));
                    if (bookDetail.getIntroduce().length() > textLeng) {
                        book_des.setText(Html.fromHtml(bookDetail.getIntroduce().substring(0, textLeng) + "..."));
                    }else {
                        book_des.setText(Html.fromHtml(bookDetail.getIntroduce()));
                    }
                    book_des.setMaxLines(4);
                }
                break;

            case R.id.back_layout:
                backToHome();
                break;
            case R.id.iv_fold_text:

                break;
            case R.id.ll_replace_bookrecommend:
                ll_replace_bookrecommend.setOnClickListener(null);
                viewRotateAnim(iv_replace_bookrecommend);
                if (!ActivityUitl.isNetworkAvailable(BookDesActivity.this) || bookDetail == null) {
                    iv_replace_bookrecommend.clearAnimation();
                    ll_replace_bookrecommend.setOnClickListener(BookDesActivity.this);
                    ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                }else {
                    BookDesRequester.replaceBookRecommend(bookDetail.getId(), bookDetail.getSortId());
                }
                break;
            case R.id.common_refresh_net:
                common_refresh_net.setOnClickListener(null);
                comon_bgbar_loading.setVisibility(View.VISIBLE);
                mLoadingInternalTime = System.currentTimeMillis() + 2000;
                if (ActivityUitl.isNetworkAvailable(BookDesActivity.this)) {
                     getData(false);
                }else {
                    common_prompt_content.setText(R.string.laikan_network_anomaly);
                    closeDelayLoading(System.currentTimeMillis());
                }
                break;
            default:
                break;
        }
    }

    private void viewRotateAnim(View view){
        Animation animation = AnimationUtils.loadAnimation(BookDesActivity.this, R.anim.img_repeat_rotate_anim);
        LinearInterpolator linearInterpolator = new LinearInterpolator();
        animation.setInterpolator(linearInterpolator);
        view.startAnimation(animation);
    }

    /**
     * 加入书架
     */
    private void collect() {

        mLoadingDialog.show();
        Map<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));

        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                try {
                    mLoadingDialog.dismiss();
                    DBBook.getInstance().insertBook(bookDes);

                    // 3.提示信息
                    collect_flag1.setText(R.string.bookshelf_already_added);
                    collect_flag1.setTextColor(getResources().getColor(R.color.C_999999));
                    ToastMgr.showShortToast(R.string.bookshelf_book_added);
                }catch (Exception e) {
                    ToastMgr.showShortToast(laikan_data_load_failed);
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                mLoadingDialog.dismiss();
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
            }

            @Override
            public void onFinish() {

            }
        };
        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_book_follow + book_id + "/2/add");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    /**
     * 保存目录列表json至sd卡中</br>
     * 保存目录列表后访问目录页
     * @param json
     * @param i2
     */
    private void saveFile(String json, int i2) {
        try {
            Thread.sleep(300);
        }catch (InterruptedException e) {
            e.printStackTrace();
        }

        File file = PublicUtil.getRootPath();
        file = new File(file.getPath() + "/LaikanReader/book/" + book_id + "/chapter");

        if (!file.isDirectory()) {
            file.delete();
            file.mkdirs();
        }
        if (!file.exists()) {
            file.mkdirs();
        }
        FileUtil.writeFile(file.getPath(), json);
        switch (i2) {
            // 下载目录后 访问目录列表页
            case 1:
                Intent intent = new Intent();
                intent.setClass(mContext, BookChapter.class);
                intent.putExtra("book_id", book_id);
                intent.putExtra("bookName", bookname);
                intent.putExtra("groupId", BookType);
                intent.putExtra("state", "1");
                intent.putExtra("writername", writername);
                // 传递书籍详情信息
                bundle = new Bundle();
                bundle.putSerializable("bookDes", bookDes);
                intent.putExtras(bundle);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;
            // 下载目录后 访问 阅读页
            case 2:
                // 找到目录列表中的第一可读章节
                int pos = 0;
                for (int i = 0; i < mData.size(); i++) {
                    if (!mData.get(i).isVolume()) {
                        pos = i;
                        break;
                    }
                }
                String flag = "";
                // 跳转到书籍的 第 pos 章节
                Intent intent1 = new Intent();
                intent1.setClass(mContext, ReaderDetailActivity.class);
                intent1.putExtra("bookId", book_id);
                intent1.putExtra("chapterid", mData.get(pos).getId());
                intent1.putExtra("bookName", bookname);
                intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent1.putExtra("pos", pos);
                intent1.putExtra("writername", writername);
                // 传递书籍详情信息
                bundle = new Bundle();

                //-----------------改-补全Book对象的sortIndex信息以便更新书架----------------
                Book book = DBBook.getInstance().queryBookById(book_id);
                if (null != book){
                    double sortIndex = book.getSortIndex();
                    bookDes.setSortIndex(sortIndex);
                }
                bundle.putSerializable("bookDes", bookDes);
                intent1.putExtras(bundle);
                startActivity(intent1);
                break;
            default:
                break;
        }

    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        SPUtil.putBoolean("Single_click", false);
    }

    /**
     * 下载目录列表
     *
     * @param i
     */
    private void loadDirectory(final int i) {
        mLoadingDialog.show();
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                mLoadingDialog.dismiss();
                BaseDataBean<BaseListDataBean<ChapterBean>> result;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<BaseListDataBean<ChapterBean>>>() {
                }.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                    ArrayList<ChapterBean> data = result.getData().getData();

                    BookFileUtils.totalChapter(book_id, data);
                }catch (JsonSyntaxException e) {
                    // 数据解析失败
                    ToastMgr.showShortToast(laikan_data_load_failed);
                    e.printStackTrace();
                    return;
                }
                if (result != null) {
                    if (null == bookDetail || !Constants.RESULT_OK.equals(result.getResult())) {
                        ToastMgr.showShortToast(result.getError_msg());
                    }else {
                        mData = result.getData().getData();
                        saveFile(httpResponse.responseContent, i);
                    }
                }else {
                    ToastMgr.showShortToast(laikan_data_load_failed);
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                mLoadingDialog.dismiss();
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                KLog.e("网络不给力，请重试。04");
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL() + "/book/" + book_id + "/chapter");
        HttpApiRequestEngine.getInstance().httpGetRequest(requester, requestListener);

    }

    public void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        oks.disableSSOWhenAuthorize();

        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(bookDetail.getName());
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl(APIProtocol.getRootURL2() + "share/" + book_id);
        // text是分享文本，所有平台都需要这个字段
        // oks.setText("我是分享文本");
        String str = "";
        if (bookDetail.getIntroduce().length() > 119) {
            str = bookDetail.getIntroduce().substring(0, 118) + "...";
        }else {
            str = bookDetail.getIntroduce();
        }
        oks.setText(str);
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        // oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");//
        // 确保SDcard下面存在此张图片
        oks.setImageUrl(bookDetail.getIcon());//
        // 确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(APIProtocol.getRootURL2() + "share/" + book_id);
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment(bookDetail.getIcon());
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl(APIProtocol.getRootURL2() + "share/" + book_id);
        // 启动分享GUI
        oks.show(this);
    }

    // 获取已下载章节id
    public List<String> getFile(File file) {

        File[] fileArray = file.listFiles();
        try {
            for (File f : fileArray) {
                if (f.isDirectory()) {
                    mFileList.add(f.getName());
                }else {
                    getFile(f);
                }
            }

        }catch (Exception e) {
            // TODO: handle exception
        }

        return mFileList;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == 102) {
            if (DBBook.getInstance().queryBookById(book_id) == null) {
                collect();
            }
        }
    }

    public boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        return isNum.matches();
    }

    private void backToHome(){
        if(isFromPoster){
            Intent intent = new Intent(mContext, HomeActivity.class);
            intent.putExtra("login_type", "login_custom");
            startActivity(intent);
            finish();
        }else{
            finish();
        }
    }

    @Override
    public void onBackPressed() {

        backToHome();
        super.onBackPressed();
    }
}
